package kyo;

public class VtMenu<I, D> extends Menu<I, D> implements InputRun {
    private Input<VtMenu<I, D>> input;
    private D inRunData = null;
    private int selIndex = 0;
    private Item<I, D> selItem = null;
    private I selInfo = null;

    public VtMenu(I title) {
        setTitle(title);
        input = new Input<VtMenu<I, D>>(this, null);
        input.regKey(Keysym.UP, Keysym.LEFT, Keysym.RIGHT, Keysym.DOWN);
        input.regKey(Keysym.RETURN);
    }

    @Override
    public <D> RunState handle(Keysym sym, StringBuilder s, D data) {
        RunState rState = RunState.RUNNING;

        switch (sym) {
            case UP:
                if (selIndex > 0) {
                    selItem = get(--selIndex);
                    selInfo = selItem.getInfo();
                    showVtMenu();
                }
                break;
            case DOWN:
                if (selIndex < getSize() - 1) {
                    selItem = get(++selIndex);
                    selInfo = selItem.getInfo();
                    showVtMenu();
                }
                break;
            case RETURN:
                if (selItem.isSubMenu()) {
                    if (selItem.getSubMenu().run())
                        return RunState.QUIT;
                    Vt.cmd(VtCmd.CLEAR);
                    showVtMenu();
                } else {
                    rState = selItem.run();
                }
                break;
        }
        return rState;
    }

    @Override
    public void showItem(int index, I itemInfo) {
        if (itemInfo.equals(selInfo)) {
            Vt.out(itemInfo.toString(), VtColor.WHITE, VtColor.BLACK);
            System.out.println();
        } else {
            System.out.println(itemInfo.toString());
        }
    }

    private void showVtMenu() {
        Vt.gotoxy(1, 1);
        showList();
    }

    @Override
    public boolean run() {
        Vt.cmd(VtCmd.CLEAR);
        selItem = get(selIndex);
        selInfo = selItem.getInfo();
        if (getLevel() == 0) {
            Vt.cmd(VtCmd.HIDE);
        }
        showVtMenu();
        RunState rState = input.run();
        if (getLevel() == 0) {
            Vt.cmd(VtCmd.SHOW);
            input.close();
        }
        return rState == RunState.QUIT ? true : false;
    }
}
